package com.ahdy.ws;

import com.ahdy.pojo.Message;
import com.google.gson.Gson;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static com.ahdy.tool.AiNutrient.AiNutrientmain;


/**
 * @version v1.0
 * @ClassName: ChatEndpoint
 * @Description: TODO(websocker)
 * @Author: 刘东宇
 */
@ServerEndpoint(value = "/chat/{id}")
@Component
public class ChatEndpoint {

    //用来存储每一个客户端对象对应的ChatEndpoint对象
    public static Map<String,ChatEndpoint> onlineUsers = new ConcurrentHashMap<>();

    //声明session对象，通过该对象可以发送消息给指定的用户
    private Session session;

    //声明一个HttpSession对象，我们之前在HttpSession对象中存储了用户名
    @OnOpen
    //连接建立时被调用
    public void onOpen(Session session,EndpointConfig config,@PathParam("id") String userid) throws IOException {
        //将局部的session对象赋值给成员session
        System.out.println("连接了");
        this.session=session;
        System.out.println("userid = " + userid);
        //将当前对象存储到容器中
        onlineUsers.put(userid,this);
        System.out.println("当 前 用 户 数 量 "+onlineUsers.size());
    }

    @OnMessage
    //接收到客户端发送的数据时被调用
    public void onMessage(String message) throws Exception {
        System.out.println("onMessage message = " + message);
        Gson gson = new Gson();
        Message mess = gson.fromJson(message, Message.class);
        //获取要将数据发送给的用户
        String id = mess.getUser();
        if (id.equals("admin")){
            AiNutrientmain(0,mess.getMsg());
        } else if (id.equals("root")) {
            AiNutrientmain(1,mess.getMsg());
        }
        //发送数据
        else if(onlineUsers.get(id)!=null){
            System.out.println("发出去了");
            onlineUsers.get(id).session.getBasicRemote().sendText(mess.getMsg());
        }else {
            System.err.println("没发，用户不在线");
        }
    }

    @OnClose
    //连接关闭时被调用
    public void onClose(Session session,@PathParam("id") String username) {
        System.out.println("username = " + username);
        onlineUsers.remove(username);
        System.out.println("走了一位！！！当前在线人数："+onlineUsers.size());
    }
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("Error occurred in session: " + session.getId()+throwable);
        try {
            session.close();
        } catch (IOException e) {
            System.out.println("Error closing session: " + session.getId()+ e);
        }
    }

}
